package cc.owoo.godpen.analysis.css;

import cc.owoo.godpen.analysis.html.Document;
import cc.owoo.godpen.analysis.html.Element;

import java.util.Queue;

/**
 * id选择器
 * Created by nimensei
 * 2022-06-01 上午 12:40
 */
public class IdSelector extends SelectorNode {
    private final String id;// ID名称

    /**
     * 创建一个id选择器节点
     *
     * @param id id名称，不能为空和为null
     */
    public IdSelector(String id) {
        if (id == null || (id = id.trim().toLowerCase()).length() == 0)
            throw new NullPointerException("id不能为空");
        this.id = id;
    }

    @Override
    void selectElement(Element element, Queue<Element> elements) {
        if (element instanceof Document document) {
            Element res = document.getElementById(id);
            if (res != null)
                elements.add(res);
            return;
        }
        for (Element child : element.getAllChildElement())
            matchingElement(child, elements);
    }

    @Override
    void matchingElement(Element element, Queue<Element> elements) {
        String elementID = element.getId();
        if (elementID == null || !elementID.equals(id))
            return;
        elements.add(element);
    }

    @Override
    public void stringify(StringBuilder string) {
        string.append('#').append(id);
    }
}
